﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace Pixeldyne.Core.Network
{
	public static class Extensions
	{
		private static readonly char[] separators = {',', ';'};

		public static int AddMulti(this MailAddressCollection mailAddressCollection, string addresses)
		{
			if (string.IsNullOrWhiteSpace(addresses))
				throw new ArgumentNullException("addresses");

			var addressList = addresses.Split(separators);

			foreach (var address in addressList)
			{
				mailAddressCollection.Add(address);
			}

			return addressList.Length;
		}

		public static bool IsValidHost(this MailAddressCollection mailAddressCollection)
		{
			return mailAddressCollection.All(mailAddress => mailAddress.IsValidHost());
		}

		public static bool IsValidHost(this MailAddress mailAddress)
		{
			try
			{
				var ipEntry = System.Net.Dns.GetHostEntry(mailAddress.Host);

				return (ipEntry.AddressList != null && ipEntry.AddressList.Length > 0);
			}
			catch
			{
				return false;
			}
		}
	}

	public class SmtpClientDirect : SmtpClient
	{
		public new void Send(MailMessage message)
		{
			if (string.IsNullOrWhiteSpace(Host))
			{
				if (message.To.Count > 0)
				{
					var addressHost = message.To[0].Host;

					var mailServers = DnsTools.GetMailRecords(addressHost);

					// grab the first-priority mail server from the dictionary
					if (mailServers.Any())
					{
						Host = mailServers.Keys.First();
					}
				}
			}

			base.Send(message);
		}
	}
}
